<template>
  <div>
    <el-form :model="contractForm" :rules="rules" ref="contractFormRef" label-width="120px">
      <el-row :gutter="20">
        <!-- 员工选择 -->
        <el-col :span="12">
          <el-form-item label="员工成员" prop="employeeId">
            <el-select 
              v-model="contractForm.employeeId" 
              placeholder="请选择员工" 
              style="width: 100%"
              @change="handleEmployeeChange"
              filterable
              remote
              :remote-method="searchEmployees"
              :loading="employeeLoading"
            >
              <el-option
                v-for="employee in employeeOptions"
                :key="employee.employeeId"
                :label="employee.employeeName"
                :value="employee.employeeId">
                <span style="float: left">{{ employee.employeeName }}</span>
                <span style="float: right; color: #8492a6; font-size: 13px">{{ employee.workNumber }}</span>
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        
        <el-col :span="12">
          <el-form-item label="工号" prop="workNumber">
            <el-input v-model="contractForm.workNumber" disabled></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="部门" prop="department">
            <el-input v-model="contractForm.department" disabled></el-input>
          </el-form-item>
        </el-col>
      
        <el-col :span="12">
          <el-form-item label="岗位" prop="post">
            <el-input v-model="contractForm.post" disabled></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="入职时间" prop="dateOfInduction">
            <el-date-picker
              v-model="contractForm.dateOfInduction"
              type="date"
              placeholder="请选择入职时间"
              style="width: 100%"
              disabled>
            </el-date-picker>
          </el-form-item>
        </el-col>
        
        <el-col :span="12">
          <el-form-item label="员工状态" prop="employeeStatus">
            <el-input v-model="contractForm.employeeStatus" disabled></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="聘用形式" prop="employmentForm">
            <el-input v-model="contractForm.employmentForm" disabled></el-input>
          </el-form-item>
        </el-col>
        
        <el-col :span="12">
          <el-form-item label="合同编号" prop="contractNumber">
            <el-input v-model="contractForm.contractNumber" placeholder="请输入合同编号"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="主合同" prop="mainContract">
            <el-select v-model="contractForm.mainContract" placeholder="请选择是否为主合同" style="width: 100%">
              <el-option label="是" value="是"></el-option>
              <el-option label="否" value="否"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        
        <el-col :span="12">
          <el-form-item label="合同类型" prop="contractType">
            <el-input v-model="contractForm.contractType" placeholder="请输入合同类型"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="合同开始日期" prop="contractStartDate">
            <el-date-picker
              v-model="contractForm.contractStartDate"
              type="date"
              placeholder="请选择合同开始日期"
              style="width: 100%">
            </el-date-picker>
          </el-form-item>
        </el-col>
        
        <el-col :span="12">
          <el-form-item label="合同结束日期" prop="contractEndDate">
            <el-date-picker
              v-model="contractForm.contractEndDate"
              type="date"
              placeholder="请选择合同结束日期"
              style="width: 100%">
            </el-date-picker>
          </el-form-item>
        </el-col>
      </el-row>
      
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="合同期限" prop="contractDuration">
            <el-input v-model="contractForm.contractDuration" placeholder="请输入合同期限"></el-input>
          </el-form-item>
        </el-col>
        
        <el-col :span="12">
          <el-form-item label="合同主体" prop="contractSubject">
            <el-input v-model="contractForm.contractSubject" placeholder="请输入合同主体"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      
      <el-row :gutter="20">
        <el-col :span="24">
          <el-form-item label="合同备注" prop="contractRemarks">
            <el-input 
              v-model="contractForm.contractRemarks" 
              type="textarea" 
              placeholder="请输入合同备注"
              :rows="3">
            </el-input>
          </el-form-item>
        </el-col>
      </el-row>
      
      <el-row>
        <el-col :span="24" style="text-align: center;">
          <el-button @click="handleCancel">取消</el-button>
          <el-button type="primary" @click="handleSubmit" :loading="submitLoading">提交</el-button>
        </el-col>
      </el-row>
    </el-form>
  </div>
</template>

<script lang="ts" setup>
import { ref, onMounted } from 'vue'
import server from '@/api/request'
import { ElMessage } from 'element-plus'
import axios from 'axios'

const emit = defineEmits(['added', 'close'])

// 表单引用
const contractFormRef = ref()

// 表单数据
const contractForm = ref({
  employeeId: null,
  employeeName: '',
  dateOfInduction: null,
  workNumber: '',
  department: '',
  post: '',
  employeeStatus: '',
  employmentForm: '',
  contractNumber: '',
  mainContract: '是',
  contractType: '',
  contractStartDate: null,
  contractEndDate: null,
  contractDuration: '',
  contractSubject: '',
  contractRemarks: ''
})

// 表单验证规则
const rules = {
  employeeId: [{ required: true, message: '请选择员工', trigger: 'change' }],
  contractNumber: [{ required: true, message: '请输入合同编号', trigger: 'blur' }],
  contractType: [{ required: true, message: '请输入合同类型', trigger: 'blur' }],
  contractStartDate: [{ required: true, message: '请选择合同开始日期', trigger: 'change' }],
  contractEndDate: [{ required: true, message: '请选择合同结束日期', trigger: 'change' }],
  contractDuration: [{ required: true, message: '请输入合同期限', trigger: 'blur' }],
  contractSubject: [{ required: true, message: '请输入合同主体', trigger: 'blur' }]
}

// 员工选项
const employeeOptions = ref([])
const employeeLoading = ref(false)
const submitLoading = ref(false)
const searchEmployees = async (query: string) => {
  employeeLoading.value = true
  try {
    const response = await server.get('/into/findPage', {
      params: {
        pageNum: 1,
        pageSize: 20,
        ...(query ? { keyword: query } : {})
      }
    })
    
    if (response.code === 200) {
      employeeOptions.value = response.data.records
    }
  } catch (error) {
    console.error('获取员工列表失败:', error)
    ElMessage.error('获取员工列表失败')
  } finally {
    employeeLoading.value = false
  }
}

// 员工选择变化时更新表单
const handleEmployeeChange = (employeeId) => {
  const selectedEmployee = employeeOptions.value.find(emp => emp.employeeId === employeeId)
  if (selectedEmployee) {
    contractForm.value.employeeName = selectedEmployee.employeeName
    contractForm.value.dateOfInduction = selectedEmployee.dateOfInduction
    contractForm.value.workNumber = selectedEmployee.workNumber
    contractForm.value.department = selectedEmployee.onboardingDepartment
    contractForm.value.post = selectedEmployee.entryPosition
    contractForm.value.employeeStatus = selectedEmployee.employeeStatus
    contractForm.value.employmentForm = selectedEmployee.employmentForm
  }
}

// 提交表单
const handleSubmit = async () => {
  if (!contractFormRef.value) return
  
  await contractFormRef.value.validate(async (valid) => {
    if (valid) {
      submitLoading.value = true
      try {
        const submitData = {
          ...contractForm.value,
          dateOfInduction: contractForm.value.dateOfInduction ? 
            new Date(contractForm.value.dateOfInduction).toISOString().split('T')[0] : null,
          contractStartDate: contractForm.value.contractStartDate ? 
            new Date(contractForm.value.contractStartDate).toISOString().split('T')[0] : null,
          contractEndDate: contractForm.value.contractEndDate ? 
            new Date(contractForm.value.contractEndDate).toISOString().split('T')[0] : null
        }
        
        const response = await server.post('/employeeContracts/add', submitData)
        if (response.code === 200) {
          ElMessage.success('合同添加成功')
          emit('added')
        } else {
          ElMessage.error('合同添加失败: ' + response.message)
        }
      } catch (error: any) {
        console.error('合同添加失败:', error)
        if (error.response && error.response.data) {
          ElMessage.error('合同添加失败: ' + (error.response.data.message || '服务器内部错误'))
        } else {
          ElMessage.error('合同添加失败: 网络错误或服务器无响应')
        }
      } finally {
        submitLoading.value = false
      }
    }
  })
}

// 取消操作
const handleCancel = () => {
  emit('close')
}

// 初始化获取员工列表
onMounted(() => {
  searchEmployees('')
})
</script>

<style scoped>
.el-row {
  margin-bottom: 20px;
}
progress-bar {
  height: 6px;
  background-color: #ccebf7;
  border-radius: 3px;
  display: flex;
  width: 100%;
  overflow: hidden;
}

.progress {
  width: 8%;
  height: 10;
  background-color: #61c3ea;
  border-radius: 3px 0 0 3px;
  transition: width 0.3s ease;
}
</style>